package edu.uc.util;

import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate5.HibernateCallback;

public final class SpringHibUtil {
	public static HibernateCallback<Object> getCallbackScalar(String hql, Object... params) {
		HibernateCallback<Object> callback = null;
		callback = new HibernateCallback<Object>() {

			@Override
			public Object doInHibernate(Session arg0) throws HibernateException {
				org.hibernate.query.Query<Object> query = null;
				query = HibUtil.createQuery(Object.class, arg0, hql, params);
				return query.uniqueResult();
			}
			
		};
		return callback;
	}
	
	public static HibernateCallback<Long> getCallbackScalarLong(String hql, Object... params) {
		HibernateCallback<Long> callback = null;
		callback = new HibernateCallback<Long>() {

			@Override
			public Long doInHibernate(Session arg0) throws HibernateException {
				org.hibernate.query.Query<Long> query = null;
				query = HibUtil.createQuery(Long.class, arg0, hql, params);
				return query.uniqueResult();
			}
			
		};
		return callback;
	}
	
	public static <E> HibernateCallback<E> getCallbackBean(Class<E> clazzBean, String hql, Object... params) {
		HibernateCallback<E> callback = null;
		callback = new HibernateCallback<E>() {

			@Override
			public E doInHibernate(Session arg0) throws HibernateException {
				org.hibernate.query.Query<E> query = null;
				query = HibUtil.createQuery(clazzBean, arg0, hql, params);
				java.util.List<E> tmpList = query.list();
				E bean = null;
				if(tmpList != null && tmpList.size() > 0) {
					bean = tmpList.get(0);
				}
				return bean;
			}
			
		};
		return callback;
	}
	
	public static <E> HibernateCallback<java.util.List<E>> getCallbackList(Class<E> clazzBean, String hql, Object... params) {
		HibernateCallback<java.util.List<E>> callback = null;
		callback = new HibernateCallback<java.util.List<E>>() {

			@Override
			public List<E> doInHibernate(Session arg0) throws HibernateException {
				org.hibernate.query.Query<E> query = null;
				query = HibUtil.createQuery(clazzBean, arg0, hql, params);
				return query.list();
			}
			
		};
		return callback;
	}
	
	public static <E> HibernateCallback<java.util.List<E>> getCallbackPager(Class<E> clazzBean, Long startIndex, Long pageSize, String hql, Object... params) {
		HibernateCallback<java.util.List<E>> callback = null;
		callback = new HibernateCallback<List<E>>() {

			@Override
			public List<E> doInHibernate(Session arg0) throws HibernateException {
				org.hibernate.query.Query<E> query = null;
				query = HibUtil.createQuery(clazzBean, arg0, hql, params);
				return query.setFirstResult(startIndex.intValue()).setMaxResults(pageSize.intValue()).list();
			}
		};
		return callback;
	}
}
